import React, { useEffect, useState } from 'react';
import { history, useSelector, useDispatch } from 'umi';
import Header from '@/components/Header/Header';
import { stringify } from 'qs';
import { queryLineLogin } from '@/services/user';
import { LineIcon } from 'react-share';
import { Message, Radio, RadioGroup } from '@/design';
import RuleModal from './components/RuleModal';
import { isEmpty } from '@/utils/common';
import { channelId } from '@/config';
import styles from './user.less';

export default function (props: any) {
  let unmount = false;
  const dispatch = useDispatch();
  const [loading, setLoading] = useState<boolean>(false);
  const [readRule, setReadRule] = useState<boolean>(true);
  const { codeDetail } = useSelector((state: any) => state.store);
  let codeId = localStorage.getItem('CODEID');
  let braId = localStorage.getItem('BRAID');



  // const [ruleVisiable, setRuleVisiable] = useState<boolean>(true);
  const [ruleParams, setRuleParams] = useState<any>({
    ruleVisiable: false,
    type: ''
  })

  useEffect(() => {
    const { code, error_description } = props.location.query;
    if (!isEmpty(error_description)) {
      handleRedirectPath()
    } else if (!isEmpty(code)) {
      fetchLineLogin(code)
    }
    return () => {
      unmount = true
    }
  }, [])

  useEffect(()=>{
    if(isEmpty(codeDetail)) {
      fetchCodeDetail();
    }
  }, [])

  const fetchCodeDetail = () => {
    dispatch({
      type: 'store/fetchCodeDetail'
    })
  }

  /* 取消 */
  const handleRedirectPath = () => {
    Message.error('登入失敗');
    history.replace('/line');
  }


  /* 閱讀用戶協議 */
  const handleshowRule = (ruleVisiable: boolean, type = '') => {
    setRuleParams({ ruleVisiable, type })
  }

  /* 其它登入 */
  const handleToOtherLogin = () => {
    history.replace('/login')
  }

  const handleLoginRedirectPath = () => {
    props.history.replace(`/getcoupon`);
    // if (history.length < 2) {
    //   history.replace('/home');
    // }
  }

  /* line登入 */
  const fetchLineLogin = async (code: string) => {
    setLoading(true);
    let result = await queryLineLogin({
      channelId,
      redirectUri: `${window.location.origin}/line`,
      code,
      regMerMember: '1', //註冊的同時成為門店的會員
      registerSource: 'fnbWeb', //數據分析
    });
    if (unmount) return false;
    setLoading(false);
    if (!result) return false;
    localStorage.setItem('userInfo', JSON.stringify(result.data  || {}));
    localStorage.setItem('TOKEN', result.data.token)
    Message.success('LINE 快捷登入成功');
    handleLoginRedirectPath();
  }

  // line登錄
  const handleLineLogin = async () => {
    console.log('BRAID')
    let lineConfig = {
      response_type: 'code',
      client_id: channelId,
      redirect_uri: `${window.location.origin}/line`,
      state: `braId=${braId}&codeId=${codeId}`,
      scope: 'openid profile email',
      nonce: 'fnb-login',
      bot_prompt: 'normal',
    }
    let path = `https://access.line.me/oauth2/v2.1/authorize?${stringify(lineConfig)}`;
    location.replace(path)
  }


  console.log(ruleParams, codeDetail)
  return <>
    <div className={styles.line_wrap}>
      <Header hasBack title={'快捷登錄'}></Header>
      <div className={styles.line_login}>
        <h3 className={styles.title}>快捷登入</h3>
        {!loading ?
          <>
            <div className={styles.icon} onClick={handleLineLogin}><LineIcon /></div>
            <p className={styles.tips}>點擊logo登入</p>
          </> : <div className="ume-spin xs"></div>
        }
      </div>
      <div className={styles.other_login}>
        {!loading && <p className={styles.title}><span>其他方式登入</span></p>}
        {!loading && <a className={styles.link} onClick={handleToOtherLogin}>註冊 / 登入</a>}
        <div className={styles.rule}>
          <div className={styles.checkbox}>
            <input type="checkbox" id='option' checked={readRule} onChange={() => setReadRule(!readRule)} />
            <label htmlFor="option">同意
          <svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M13 50.986L37.334 75 88 25" strokeWidth="6" stroke="#02ADDA" fill="none" fillRule="evenodd" strokeDasharray="150" strokeDashoffset="150" /></svg>
            </label>
          </div>
          <a onClick={() => handleshowRule(true, 'member')}>《ume商戶會員使用協議》</a>
          <span>與</span>
          <a onClick={() => handleshowRule(true, 'prvacy')}>《商戶會員隱私協議》</a>
        </div>
      </div>
    </div>
    <RuleModal {...ruleParams} onClose={() => setRuleParams({ ruleVisiable: false })} />
  </>
}